﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;

using SBPweb.Modules.Modularity;

namespace SBPweb.Services.Host.Controls
{
    public partial class Services : System.Web.UI.UserControl
    {

        #region Property accessors

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            dgServices.DataSourceID = null;
            dgServices.DataSource = Global.ApplicationHost.ModuleDescriptors.Values;
            dgServices.DataBind();
        }

        protected void dgServices_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Button lbDisco = (Button)e.Item.FindControl("lbDisco");
                Button lbLoad = (Button)e.Item.FindControl("lbLoad");
                Button lbUnload = (Button)e.Item.FindControl("lbUnload");
                ModuleDescriptor md = e.Item.DataItem as ModuleDescriptor;
                lbDisco.Enabled = md.Loaded && md.Initialized;
                lbDisco.CommandArgument = md.ModuleTypeName;
                lbLoad.Enabled = !md.Loaded;
                lbLoad.CommandArgument = md.ModuleTypeName;
                lbUnload.Enabled = md.Loaded;
                lbUnload.CommandArgument = md.ModuleTypeName;
            }
        }

        protected void dgServices_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            string itemName = e.CommandArgument.ToString();
            ModuleInfo mI;
            lock (Global.ApplicationHost.ModuleInfos)
            {
                if (Global.ApplicationHost.ModuleInfos.ContainsKey(itemName))
                {
                    mI = Global.ApplicationHost.ModuleInfos[itemName];
                }
                else
                {
                    Global.ApplicationHost.ModuleInfos.Add(itemName, mI = new ModuleInfo(Global.ApplicationHost.ModuleDescriptors[itemName], false, true, false));
                }
            }
            switch (e.CommandName)
            {
                default:
                case "disco":
                    Response.Redirect(string.Format("/{0}.ashx", itemName));
                    break;
                case "load":
                    Global.ApplicationHost.ModuleLoader.LoadModule(mI);
                    break;
                case "unload":
                    Global.ApplicationHost.ModuleLoader.UnloadModule(mI);
                    break;
            }
            BindData();
        }
    }
}